package pl.webshop;

import java.lang.String;
import java.lang.Integer;
import java.lang.Float;
import java.util.Hashtable;
import java.util.Enumeration;
import javax.servlet.http.*;


public class Cart {
	protected Hashtable<String,String[]> items = new Hashtable<String,String[]>();

	  public void addItem(String itemId, String product_name, float price) {
	    String[] newItem = {itemId, product_name, Float.toString(price), "1"};
	    if (items.containsKey(itemId)) {

	      String[] Item = (String[])items.get(itemId);
	      int tmpQuantity = Integer.parseInt(Item[3]);
	      tmpQuantity = tmpQuantity + 1;
	      Item[3] = Integer.toString(tmpQuantity);
	    }
	    else {
	      items.put(itemId, newItem);
	    }
	  }

	  public void removeItem(String itemId) {
	    if (items.containsKey(itemId)) {
	    	 String[] Item = items.get(itemId);
	    	 if(Integer.parseInt(Item[3]) > 1)
	    	 {
	    		 Item[3] = Integer.toString(Integer.parseInt(Item[3]) - 1);
	    		 items.put(itemId, Item);
	    	 }
	    	 else
	    	 {
	    		 items.remove(itemId);
	    	 }
	    	 
	    }
	  }
	  
	  public Enumeration<String[]> getElements() {

	    return items.elements();
	  }

	  public float getCost() {

	    Enumeration<String[]> e = items.elements();
	    String[] Item;
	    float totalCost = 0.00f;

	    while (e.hasMoreElements()) 
	    {
	    	Item = e.nextElement();
	    	totalCost += (Float.parseFloat(Item[3]) * Float.parseFloat(Item[2]));
	    }
	    return totalCost;
	  }

	  public int getNumOfItems() {

	    Enumeration<String[]> e = items.elements();
	    String[] Item;
	    int numOfItems = 0;

	    while (e.hasMoreElements()) {

	      Item = e.nextElement();
	      numOfItems += Integer.parseInt(Item[3]);
	    }

	    return numOfItems;
	  }
	  
	  public void checkRequest(HttpServletRequest request)
	  {
		  String id = request.getParameter("id");
		  String submit = request.getParameter("Submit");
		    if ( id != null ) {
		    	if(submit.equals("Add"))
		    	{
		    		String product_name = request.getParameter("product_name");
		          	Float price = new Float(request.getParameter("price"));          
		          	addItem(id, product_name, price.floatValue());
		    	}
		    	else if(submit.equals("RemoveItem"))
		    	{
		    		removeItem(id);
		    	}
		    } else if(submit != null)
		    {	
		    	if(submit.equals("RemoveAll"))
		    	{
		    		items.clear();
		    	}	    	
		    }
	  }
	  
	  public int checkBuy(HttpServletRequest request)
	  {
		  String buy = request.getParameter("Buy");
		  if(buy != null)
		  {
			  int numberOfItems = this.getNumOfItems();
			  items.clear();
			  return  numberOfItems;
		  }
		  return 0;
	  }
}
